<template>
  <view id="switchPage">
    <!-- 顶部搜索框 -->
    <view class="search-header">
      <u-input v-model="searchCode" type="text" placeholder-style="backgroundColor: #efeff1;height: 70rpx;lineHeight: 70rpx;padding: 0 20rpx;" style="marginRight: 20rpx;" />
      <!-- <u-icon name="scan" size="60" @click="scanQrCode(0)"></u-icon> -->
      <image class="header-filter-img" src="/static/img/terminalSwitch/icon-scan.png"></image>
    </view>
    <!-- 顶部 统计和过滤 -->
    <view class="total-filter">
      <view class="total">共有{{machineTotal}}台机具</view>
      <view class="filter" @click="filterClick">
        批量筛选 <image class="filter-img" src="/static/img/terminalSwitch/icon-filter.png"></image>
      </view>
    </view>
    <!-- 机具列表 -->
    <view class="machine-list">
		<mescroll-uni :fixed="false" @init="mescrollInit" :height="height" :down="downOption" @down="downCallback"
			:up="upOption" @up="upCallback" >
      <u-checkbox-group @change="checkboxGroupChange">
        <u-checkbox v-model="item.checked" v-for="(item,index) in machineList" :key="index" :name="item.id" style="width: 100%;">
          <view class="machine-name">机具编号</view>
          <view class="machine-code">{{item.snNo}}</view>
        </u-checkbox>
      </u-checkbox-group>
	  </mescroll-uni>
    </view>

    <!-- 底部 按钮 -->
    <view class="fixed-btns">
      <u-button class="all-btn" type="primary" @click="checkedAll" :disabled="isDisabled">{{machineSelected.length === machineList.length ? '全不选' : '全选'}}</u-button>
      <u-button class="switch-btn" type="primary" :disabled="isDisabled" @click="switchMachine">切换清单{{machineSelected.length}}台</u-button>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup v-model="filterPopupShow" mode="center" border-radius="14" :mask-close-able="false" width="700rpx">
      <view class="filter-title">筛选条件</view>
      <view class="filter-content">
        <view class="filter-sec-title">机具编号区间：</view>
        <view class="filter-area">
          <u-input class="filter-input" v-model="filterObj.code_start" type="text" placeholder="起始机具编号" />
          <!-- <u-icon name="scan" size="36" @click="scanQrCode(1)"></u-icon> -->
          <image class="filter-img" src="/static/img/terminalSwitch/icon-scan.png"></image>
        </view>
        <view class="filter-area">
          <u-input class="filter-input" v-model="filterObj.code_end" type="text" placeholder="结束机具编号" />
          <!-- <u-icon name="scan" size="36" @click="scanQrCode(2)"></u-icon> -->
          <image class="filter-img" src="/static/img/terminalSwitch/icon-scan.png"></image>
        </view>
        <u-button class="filter-cancel" size="medium" @click="filterCancel">取消</u-button>
        <u-button class="filter-submit" type="primary" size="medium" @click="filterSubmit">确定</u-button>
      </view>
    </u-popup>

    <!-- 切换机具弹窗 -->
    <u-popup v-model="switchPopupShow" mode="bottom" border-radius="14" :mask-close-able="false" :closeable="true" @close="switchPopupClose">
      <view class="filter-title">确认切换将会更改机具所属政策，请谨慎操作</view>
      <view class="switch-content">
        <view class="switch-tip">待切换{{switchLists.length}}台：</view>
        <u-button class="switch-link-btn" @click="toSwitchLinkPage">
          <view v-if="linkName" class="link-name">
            由 <view class="red-font"> {{pageTitle}}</view> 切换至 <view class="red-font"> {{linkName}}</view>
          </view>
          <view v-else>请选择要切换的业务线</view>
          <u-icon class="minus-icon" name="arrow-rightward" size="32"></u-icon>
        </u-button>
        <view class="switch-machine-list">
          <view class="one-machine" v-for="(item,index) in switchLists" :key="index" :name="item">
            <u-icon class="minus-icon" name="minus-circle" size="36" @click="deleteMachine(item, index)"></u-icon>
            <view>
              <view class="machine-name">机具编号</view>
              <view class="machine-code">{{item.snNo}}</view>
            </view>
          </view>
        </view>
        <view class="btn-area">
          <u-button class="clear-cancel" @click="clearAllMachine">清空</u-button>
          <u-button class="confirm-switch" type="primary" @click="submitSwitchMachine">确认切换</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 切换业务线弹窗 -->
    <u-popup v-model="switchLinkPopupShow" class="switch-link-popup" mode="bottom" border-radius="0" :mask-close-able="false">
      <view class="popup-title">
        <u-icon class="minus-icon" name="arrow-left" size="36" @click="closeLinkPopup(item, index)"></u-icon>
        <text>选择切换业务线</text>
        <text></text>
      </view>
      <view id="switchLink">
        <view class="title">
          请选择要将<text class="name">{{linkName}}</text>机具切换至以下哪个业务线?
        </view>
        <view class="switch-machine-list">
          <view class="one-machine" v-for="(item,index) in businessLines" :key="index" :name="item" @click="selectItem(item, index)">
            <view style="line-height: 36rpx;">
              <text class="item-name">{{ item.name }} </text>
              <text class="header">{{ item.percentage }}</text>
              <text class="item-yj">{{ item.yj }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
const api = require('../../config/api')
const util = require('../../utils/util')
export default {
	mixins: [MescrollMixin], // 使用mixin
  name: 'switchPage',
  data() {
    return {
      value: '', // 当前页面ID
      pageTitle: '', // 页面标题
      searchCode: '', // 搜索框输入内容
      filterPopupShow: false, // 筛选弹窗显示状态
      switchPopupShow: false, // 切换弹窗显示状态
      isDisabled: false, // 按钮禁用状态
      filterObj: {
        // 筛选条件对象
        code_start: '', // 起始机具编号
        code_end: '' // 结束机具编号
      },
      machineList: [],
      machineTotal: 0, // 机具总数
      machineSelected: [], // 已选中的机具列表
      linkName: '', // 业务线名称
      switchLinkPopupShow: false, // 切换业务线弹窗显示状态
      // 业务线数据列表，包含POS机具的各种业务方案
      businessLines: [],
      switchParams: {
        sn: '',
        startSn: '',
        endSn: '',
        value: '',
        // page: 1,
        // limit: 20
      },
      switchLists: [] ,// 要切换的机具清单
	  downOption: {
	  	auto: true //  false 不自动加载 (mixin已处理第一个tab触发downCallback)  true
	  },
	  upOption: {
	  	auto: false, // 不自动加载
	  	noMoreSize: 4,
	  	textLoading: '加载中 ...', // 加载中的提示文本
	  	textNoMore: '暂无更多', // 没有更多数据的提示文本
	  	empty: {
	  		tip: '暂无相关数据', // 提示
	  	},
	  },
	  itvalue:''
    }
  },
  onLoad(options) {
    let businessObj = uni.getStorageSync('businessItem') || {}
    // let title = businessObj.namePre.replaceAll('\n', ' ')
	let title = businessObj.name + businessObj.percentage + businessObj.yj 
    this.pageTitle = title
    uni.setNavigationBarTitle({
      title: title
    })
    this.switchParams.value = options.value
    if (options.from && options.from === 'link') {
      this.switchPopupShow = true
    }
    this.getBusinessLines()
	// this.downCallback();
    // this.getMachineList()
  },
  methods: {
    // 获取业务线列表
    getBusinessLines() {
      util.request(api.machineChangeUrl+'/'+this.switchParams.value, {}, 'POST').then((res) => {
        console.log(res)
        if (res.code !== 0) {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        } else {
          this.businessLines = (res.data || []).map((item) => {
            let names = item.name.split('\n')
            let newObj = {
              value: item.value,
              namePre: item.name,
              name: names[0],
              percentage: names[1],
              yj: names[2]
            }
            return newObj
          })
        }
      })
    },
 
	/*下拉刷新的回调 */
	downCallback() {
		// 这里加载你想下拉刷新的数据, 比如刷新轮播数据
		// loadSwiper();
		// 下拉刷新的回调,默认重置上拉加载列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
		this.mescroll.resetUpScroll()
	},
	/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
	upCallback(page) {
		//联网加载数据
		// this.mescroll.endErr();
		let pageNum = page.num; // 页码, 默认从1开始
		// let pageSize = page.size; // 页长, 默认每页10条
			let pageSize = 20; // 页长, 默认每页10条
		const res = util.request(
		//  terminalDetailUrl
			api.machineListUrl, {
				page: pageNum,
				limit: pageSize,
				...this.switchParams
			},
			'POST'
		).then(res => {
			console.log(res);
			//联网成功的回调,隐藏下拉刷新和上拉加载的状态;
			// let totalPage = res.data.pages;
			// this.mescroll.endByPage(res.data.length, totalPage); //必传参数(当前页的数据个数, 总页数)
			// this.machineList = (res.data || []).map((val) => {
			// 	val.checked = false
			// 	return val
			// })
			
			let totalSize = res.data.total;
			
			this.mescroll.endBySize(res.data.records.length, totalSize);
			//设置列表数据
			if (page.num == 1) this.machineList = []; //如果是第一页需手动制空列表
			this.machineList = this.machineList.concat(res.data.records); //追加新数据
			this.machineTotal = res.data.total || 0
		}).catch(() => {
			//联网失败, 结束加载
			this.mescroll.endErr();
		})
	},
   // 获取机具列表
    getMachineList(item) {
      util.request(api.machineListUrl, this.switchParams, 'POST').then((res) => {
        console.log(res)
        if (res.code !== 0) {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        } else {
          this.machineList = (res.data.records || []).map((val) => {
            val.checked = false
            return val
          })
          this.machineTotal = res.data.length || 0
        }
      })
    },
    // 复选框组变化事件（当任一复选框状态改变时触发）
    checkboxGroupChange(e) {
      console.log(e)
      this.machineSelected = e // 更新已选中的机具列表
    },

    // 全选/全不选功能
    checkedAll() {
      console.log(111)
      uni.showLoading({
        title: '操作中……',
        mask: true
      })
      this.isDisabled = true // 禁用按钮防止重复点击

      // 如果已全选，则执行全不选操作
      if (this.machineSelected.length === this.machineList.length) {
        setTimeout(() => {
          this.machineList.map((val) => {
            val.checked = false
            return val
          })
          this.machineSelected = []
          this.isDisabled = false
          uni.hideLoading()
        }, 800)
      } else {
        // 否则执行全选操作
        setTimeout(() => {
          this.machineList.map((val) => {
            val.checked = true
            return val
          })
          this.machineSelected = this.machineList
          this.isDisabled = false
          uni.hideLoading()
        }, 800)
      }
    },

    // 切换到机具清单页面
    switchMachine() {
      this.switchLists = this.machineList.filter(item => item.checked)
      if (this.switchLists.length === 0) {
        uni.showToast({
          title: '请选择机具',
          icon: 'none'
        })
        return
      }
      this.switchPopupShow = true // 显示切换弹窗
    },

    // 切换弹窗关闭事件
    switchPopupClose() {
      this.switchLists = [] // 清空切换清单
      this.linkName = ''
    },

    // 显示筛选弹窗
    filterClick() {
      this.filterPopupShow = true
    },

    // 扫描二维码
    scanQrCode(posi) {
      // posi参数决定扫描结果放入哪个输入框
      // 0:搜索框 1:起始编号 2:结束编号
      uni.scanCode({
        onlyFromCamera: true, // 只能从相机扫码
        scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417'], // 支持的扫码类型
        autoDecodeCharset: true, // 自动识别字符编码
        autoZoom: false, // 是否自动放大
        barCodeInput: false, // 是否支持手动输入条形码
        success: (res) => {
          this.filterPopupShow = false
          if (type === 0) {
            this.searchCode = res.result
            this.filterSubmit()
          } else if (type === 1) {
            this.filterObj.code_start = res.result
          } else if (type === 2) {
            this.filterObj.code_end = res.result
          }
        },
        fail: (error) => {
          console.log(error)
        }
      })
    },

    // 取消筛选
    filterCancel() {
      this.filterObj.code_start = ''
      this.filterObj.code_end = ''
      this.filterPopupShow = false
    },

    // 提交筛选
    filterSubmit() {
      // 调用接口进行筛选
    },

    // 从切换清单中删除指定机具
    deleteMachine(val, inx) {
      this.switchLists.splice(inx, 1)
    },

    // 清空切换清单
    clearAllMachine() {
      // 清空切换清单
      this.switchLists = []
    },

    // 提交切换
    submitSwitchMachine() {
      if (this.linkName === '') {
        uni.showToast({
          title: '请选择业务线',
          icon: 'none'
        })
        return
      }
      if (this.switchLists.length === 0) {
        uni.showToast({
          title: '请选择要切换的机具',
          icon: 'none'
        })
        return
      }
      let sns = this.switchLists.map((val) => {
        return val.snNo 
      })
      // 提交切换，调用接口
      this.switchLinkPopupShow = false
      util.request(api.updateTerminalUrl, { sns, value: this.itvalue }, 'POST').then((res) => {
        console.log(res)
        if (res.code !== 0) {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        } else {
			this.switchPopupShow = false
			uni.showToast({
			  title: "操作成功",
			  icon: 'none'
			})
			this.downCallback();
          // this.machineList = res.data || []
          // this.machineTotal = res.data.length || 0
        }
      })
    },
    // 打开业务线选择弹框
    toSwitchLinkPage() {
      this.switchLinkPopupShow = true
      // uni.navigateTo({
      //   url: '/pages/terminalSwitch/switchLink'
      // })
    },

    // 选择业务线项目
    selectItem(it, ix) {
		// console.log(it);
		this.itvalue = it.value
      // 将选择的业务线信息存入缓存
      // uni.setStorageSync('linkName', `电签 ${it.percentage} ${it.type === 1 ? it.name : ' 押金' + it.yj + ' 流量卡' + it.card}`)
      this.linkName = `${it.name} ${it.percentage} ${it.yj}`
      this.switchLinkPopupShow = false
    },
    // 关闭业务线选择弹窗
    closeLinkPopup() {
      this.switchLinkPopupShow = false
	  
    }
  }
}
</script>
<style>
	page {
		height: 100%;
		/* background-color: #F5F1F0; */
	}

	.mescroll-upwarp {
		min-height: 0rpx !important;
	}
</style>
<style lang="scss">
#switchPage {
  height: calc(100vh - 120rpx);
  margin: 0 20rpx;
  // padding-bottom: 80rpx;
  display: flex;
  flex-direction: column;

  .red-font {
    color: #f00;
  }

  .header-filter-img {
    width: 56rpx;
    height: 56rpx;
  }

  .filter-img {
    width: 36rpx;
    height: 36rpx;
  }

  .search-header,
  .total-filter {
    height: 90rpx;
    padding: 10rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .total-filter {
    .total {
    }

    .filter {
      display: flex;
      align-items: center;
      font-size: 28rpx;
    }
  }

  ::v-deep .machine-list {
    flex-grow: 1;
    padding-bottom: 20rpx;
    overflow: auto;

    .u-checkbox__label {
      color: #000;
      margin-left: 20rpx;
      font-size: 26rpx;
    }
  }

  .fixed-btns {
    position: fixed;
    bottom: 10rpx;
    left: 20rpx;
    right: 20rpx;
    display: flex;
    align-items: center;

    .all-btn {
      background-color: #333333;
      color: #ffffff;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;

      &.u-btn--primary--disabled {
        color: #ffffff !important;
        border-color: #999999 !important;
        background-color: #999999 !important;
      }

      &::after {
        border: none;
      }
    }

    .switch-btn {
      flex-grow: 1;
      // background-color: #6a9ffb;
      // color: #ffffff;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;

      &::after {
        border: none;
      }
    }
  }

  .filter-title {
    color: #000;
    padding: 20rpx;
    border-bottom: 1rpx solid #f2f2f2;
  }

  .filter-content {
    padding: 0 20rpx 20rpx;
    text-align: center;

    .filter-sec-title {
      color: #000;
      padding: 10rpx 0 0;
      text-align: left;
    }

    .filter-area {
      border: 1rpx solid #f2f2f2;
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20rpx;
      margin-top: 20rpx;

      .filter-input {
        margin-right: 20rpx;
      }
    }

    .filter-cancel {
      margin-top: 20rpx;
      margin-right: 20rpx;
    }

    .filter-submit {
      margin-top: 20rpx;
    }
  }

  .switch-content {
    padding: 0 20rpx 20rpx;

    .switch-tip {
      padding: 20rpx 0;
    }

    .switch-link-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 20rpx;
      padding: 0 10rpx;

      .link-name {
        // 换行多行
        white-space: pre-wrap;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-height: 32rpx;
      }
    }

    .switch-machine-list {
      max-height: 30vh;
      margin: 20rpx 0;
      overflow: auto;
      .one-machine {
        display: flex;
        align-items: center;
        padding: 10rpx 0;
        border-top: 1rpx solid #f2f2f2;
        font-size: 26rpx;
        .minus-icon {
          margin-right: 10rpx;
        }
      }
    }

    .btn-area {
      display: flex;
      align-items: center;

      .clear-cancel {
        flex-grow: 1;
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        background-color: #333333;
        color: #ffffff;
        &::after {
          border: none;
        }
      }

      .confirm-switch {
        flex-grow: 8;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
  }

  ::v-deep .switch-link-popup .u-drawer-content {
    padding: 20rpx;
    height: 100% !important;
    overflow: auto;

    .popup-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  #switchLink {
    padding: 20rpx;
    .title {
      color: #666;
      margin-bottom: 20rpx;
      .name {
        color: #f00;
      }
    }

    .switch-machine-list {
      padding-bottom: 20rpx;
      overflow: auto;

      .one-machine {
        display: flex;
        align-items: center;
        padding: 15rpx 20rpx;
        border: 1rpx solid #f2f2f2;
        font-size: 24rpx;
        margin-bottom: 20rpx;

        .item-yj {
          margin-left: 20rpx;
        }
      }
    }
  }
}
</style>